<?php

namespace App\Api\Three\ShopA;


/**
 * https://docs.qq.com/doc/DRUlEamNJWFFhVmVR
 */

use Monolog\Logger;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RotatingFileHandler;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Cache;
use App\Api\ChannelApi;

class NanjingLianTongAse
{
    //访问地址
    protected $appKey = ''; //系统标识
    protected $url = ''; //访问地址
    protected $secret = '';
    protected $source = '';
    protected $log = null;
    protected $appCode = null;
    protected $HMACMD5 = null;
    protected $aes  = null;
    public function __construct($appKey, $url, $secret, $source)
    {
        $this->log = new Logger('QiaoLianTongAse');
        $this->log->pushHandler(
            (new RotatingFileHandler(storage_path('/logs/QiaoLianTongAse.log'), 14, Logger::DEBUG, true, 0777))->setFormatter(new LineFormatter(null, null, true, true))
        );
        $this->appCode = $appKey;
        $this->url = $url;
        $this->HMACMD5 = $secret;  //md5
        $this->aes = $source; //aes
    }
    function send($data, $method)
    {
        $url = $this->url . $method . '?secretKey=' . $this->aes;
        // uuid
        $uuid = $this->uuid();
        // 生成时间戳
        $timestamp = $this->getTimestamp();
        $head = [
            'sign' => $this->genSign($uuid, $timestamp),
            'timestamp' => $timestamp,
            'uuid' => $uuid
        ];
        $reqObj = [
            'head' => $head,
            'body' => $data
        ];
        // var_dump($reqObj);
        // $reqObj = $this->encryptAes(json_encode($reqObj), $this->aes);
        // $reqObj = $this->encrypt(json_encode($reqObj), $this->aes);

        $reqParam = [
            'appCode' => $this->appCode,
            'requestInfo' => $reqObj
        ];
        // var_dump(json_encode($reqParam), 4444444444);
        $reqParam['requestInfo'] = $reqObj = $this->encryptAes(json_encode($reqObj), $this->aes);
        $reqParam = "{appCode:'" . $this->appCode . "',requestInfo:'" . $reqObj . "'}";
        // $paramsSend = [
        //     'requestInfo' => '',
        // ];
        $res =  $this->sendPost($url, $reqParam);
        // var_dump($res, 3333333333);
        if (is_string($res)) {
            $res = json_decode($res, true);
            if (!empty($res['responseInfo'])) {
                $res['responseInfo'] = json_decode($this->decryptKey($res['responseInfo'], $this->aes), true);
            }
        }
        // decryptKey();
        // var_dump($res);
        $this->log->info('链接:' . $url . '参数:' . json_encode($data) . '返回结果:' . json_encode($res));
        if (!empty($res['responseInfo']['body']) && $res['responseInfo']['body']['DATA']) {
            return json_encode($res['responseInfo']['body']['DATA']);
        }
        // var_dump($res['responseInfo']['body'], 777777777777);
        return json_encode($res);
    }
    /**
     * uuid 唯一序列码
     * @param string $prefix
     * @return string
     */
    function uuid($prefix = '')
    {
        $chars = md5(uniqid(mt_rand(), true));
        $uuid = substr($chars, 0, 8) . '-';
        $uuid .= substr($chars, 8, 4) . '-';
        $uuid .= substr($chars, 12, 4) . '-';
        $uuid .= substr($chars, 16, 4) . '-';
        $uuid .= substr($chars, 20, 12);
        return $prefix . $uuid;
    }
    //获取当前时间毫秒
    function msectime()
    {
        list($msec, $sec) = explode(' ', microtime());
        $msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
        return $msectime;
    }

    // 时间戳
    function getTimestamp()
    {
        date_default_timezone_set('PRC');
        return date('Y-m-d H:i:s');
        $time = $this->msectime();
        return date('Y-m-d H:i:s.') . substr($time, -3);
    }
    // 生成签名
    function genSign($uuid, $timestamp)
    {
        // $dataStr = 'uuid' . $uuid .  'timestamp' . $timestamp .  'appCode' . $this->appCode . $this->aes;
        // $this->aes = 'secretKey';
        // $this->appCode = '123456';
        $timestamp = str_replace(' ', '', $timestamp);
        $dataStr =     'appCode' . $this->appCode . 'timestamp' . $timestamp . 'uuid' . $uuid . $this->aes;
        // return $this->encodeHexString($this->md5Hex($dataStr));
        return strtolower((md5($dataStr)));
        return $this->sign($this->aes, $dataStr);
    }
    public function encodeHexString(array $bytes)
    {
        $LOWER   = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
        $length  = count($bytes);
        $charArr = [];
        foreach ($bytes as $value) {
            $value     = intval($value);
            $charArr[] = $LOWER[$this->uright(0xF0 & $value, 4)];
            $charArr[] = $LOWER[0x0F & $value];
        }
        return implode("", $charArr);
    }

    /** php 无符号右移 */
    public function uright($a, $n)
    {
        $c = 2147483647 >> ($n - 1);
        return $c & ($a >> $n);
    }

    /**
     * 模拟DigestUtils.md5
     * @param    [string]                   $string 加密字符
     * @return   [array]                           加密之后的byte数组
     * @author   Lerko
     * @dateTime 2018-01-25T09:28:33+0800
     */
    public function md5Hex($string)
    {
        return unpack("c*", md5($string, true));
    }

    /**
     * 签名
     * @param key 密钥  联通侧提供的HmacMD5
     * @param dataStr appCode+appCode值+timestamp+timestamp值*+uuid+uuid值+HmacMD5密钥值
     */
    function sign($key, $dataStr)
    {
        return base64_encode(hash_hmac("md5", $dataStr, base64_decode($key), true));
    }

    /**
     *AES加密
     */
    function encryptAes($data, $key)
    {
        // var_dump($key, 555555555);
        $data = openssl_encrypt($data, 'AES-128-ECB', $this->encryptKey($key), OPENSSL_RAW_DATA);
        return base64_encode(($data));
    }

    function  encryptKey($key)
    {
        $key = substr(openssl_digest(openssl_digest($key, 'sha1', true), 'sha1', true), 0, 16);
        // $key = openssl_digest(openssl_digest($key, 'sha1', true), 'sha1', true);
        // var_dump(($key), 1111111111);
        return ($key);
    }
    function decryptKey($data, $key)
    {
        $data = openssl_decrypt($data, 'AES-128-ECB', $this->encryptKey($key));
        return $data;
    }

    function sendPost($url, $post_data)
    {
        $opt_data = $post_data;
        if (is_array($post_data)) {
            $opt_data = json_encode($post_data);
        }


        $header = array();
        $header[] = 'Accept:application/json';
        $header[] = 'Content-Type:application/json;charset=utf-8';
        // var_dump($url);
        // var_dump($header);
        // var_dump($opt_data);
        $curl = curl_init();  //初始化
        curl_setopt($curl, CURLOPT_URL, $url);  //设置url
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $opt_data);
        // curl_setopt($curl,CURLOPT_POST,1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        //从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        //post请求
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($curl, CURLOPT_POST, 1);

        $result = curl_exec($curl);
        // var_dump($result);
        if ($result === false) {
            echo curl_errno($curl);
            exit();
        }

        curl_close($curl);
        return $result;
    }
}
